package com.cary.web;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Timer;
import java.util.TimerTask;

public class WebViewActivity extends AppCompatActivity {
    private String TAG = WebViewActivity.class.getSimpleName();

    private WebView webView;
    private LinearLayout llProgress;
    private TextView tvProgress;
    private String webUrl = "";
    private Timer timer;
    private static final int MSG_SCROLL = 0x0001;
    private static final int MSG_PROGRESS = 0x0002;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_web_view);
        webView = findViewById(R.id.web_view);
        llProgress = findViewById(R.id.ll_progress);
        tvProgress = findViewById(R.id.tv_progress);

        webUrl = getIntent().getStringExtra("webUrl");
        if (!TextUtils.isEmpty(webUrl)) {
            initWebView(webUrl);
        } else {
            Toast.makeText(this, "加载网页失败，请联系开发者", Toast.LENGTH_SHORT).show();
        }


    }

    //加载webview的方法
    private void initWebView(String url) {
        final WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);//是否支持JavaScrip
        webSettings.setDefaultTextEncodingName("utf-8");//设置解码时默认编码
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                llProgress.setVisibility(View.GONE);
                Log.d(TAG, "加载完成");
                handler.sendEmptyMessageDelayed(MSG_SCROLL,2000);
            }

            @Override //页面启动的时候
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

        });
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                Message message = new Message();
                message.what = MSG_PROGRESS;
                message.arg1=newProgress;
                handler.sendMessage(message);
             }
        });
        webView.loadUrl(url);
    }

    //调用此方法可滚动到底部
    private void scrollToBottom() {
        webView.scrollTo(0, 1000);
        webView.loadUrl("javascript:void(0)");
        startTimer();
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            switch (message.what) {
                case MSG_PROGRESS:
                    tvProgress.setText("正在加载..... "+message.arg1+" %");
                    break;
                case MSG_SCROLL:
                    scrollToBottom();
                    break;
            }
            return false;
        }
    });

    private void startTimer() {
        if (timer != null) {
            stopTimer();
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Intent intent = getIntent();
                intent.putExtra("readNum", 10);
                setResult(1000, intent);
                stopTimer();
                finish();
            }
        }, 3000);
    }

    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();//返回上个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);//退出H5界面
    }
}
